package servlet.reader;

import entity.Borrow_card;
import net.sf.json.JSONObject;
import service.reader.RegisterService;
import service.reader.impl.RegisterServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * RegisterServlet
 *
 * @author lenovo
 * @since 2023/9/7
 */
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    //引入服务层
    RegisterService service = new RegisterServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf8");
        PrintWriter out = resp.getWriter();
        JSONObject json=new JSONObject();

        String user = req.getParameter("user");
        String psw = req.getParameter("psw");

        int code = 1;
        String msg = "";

        if (user != null && user.trim().equals("")) {
            msg = "账号不能为空";
        } else if (psw != null && psw.trim().equals("")) {
            msg = "密码不能为空";
        }else {
            int add = service.add(user, psw);
            Borrow_card card = service.getId(psw, user);
            if (add == 1) {
                code = 0;
                msg = "注册成功 您的id为:"+card.getId();

                json.put("url", req.getContextPath() + "/loginReader.jsp");
            } else {
                msg = "注册失败";
            }
        }
        json.put("code",code);
        json.put("msg",msg);
        json.put("data",null);

        out.print(json.toString());
    }
}
